package com.tongzhan.service;

import com.alibaba.fastjson.JSON;
import com.tongzhan.base.BaseCriteria;
import com.tongzhan.base.BaseShareService;
import com.tongzhan.base.Return;
import com.tongzhan.entity.User;
import com.tongzhan.entity.religion.Duties;
import com.tongzhan.utils.JwtUtil;
import com.tongzhan.vo.UserVo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author hongjianbin
 * @date 2020/7/14
 */
@Service
public class InfoService extends BaseShareService {

    /**
     * 新增乡贤用户
     *
     * @param user
     * @return
     */
    public long addUser(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setIsDelete(0);
        user.setType(2);
        User save = userRepository.save(user);
        if (save != null) {
            return 1L;
        }
        return 0L;
    }

    /**
     * 修改密码
     *
     * @param userId
     * @param newPassword
     * @return
     */
    public long changePassword(String userId, String newPassword) {
        User user = findUserById(userId);
        user.setPassWord(newPassword);
        user.setUpdateTime(LocalDateTime.now());
        long l = userRepository.updateByPrimaryKeySelective(user);
        if (l > 0) {
            return 1;
        }
        return 0;
    }

    /**
     * 获取用户分页数据
     *
     * @param page
     * @param size
     * @return
     */
    public List getUserList(Integer page, Integer size) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<UserVo> list1 = new ArrayList<>();
        List<UserVo> list2 = new ArrayList<>();
        List<UserVo> list3 = new ArrayList<>();
        List<UserVo> list4 = new ArrayList<>();

        //根据类型分类
        //page1是 侨台办 列表
        PageRequest pof = PageRequest.of(page, size, Sort.Direction.DESC, "CreateTime");
        Page<User> page1 = userRepository.findPage(new Query().addCriteria(BaseCriteria.where("isDelete").is(0).and("type").is(2).and("dutiesCode").is("21")), pof);
        //page2是 侨联 列表
        Page<User> page2 = userRepository.findPage(new Query().addCriteria(BaseCriteria.where("isDelete").is(0).and("type").is(2).and("dutiesCode").is("22")), pof);
        //page3是 华侨 列表
        Page<User> page3 = userRepository.findPage(new Query().addCriteria(BaseCriteria.where("isDelete").is(0).and("type").is(2).and("dutiesCode").is("23")), pof);
        //page4是 乡镇 列表
        Page<User> page4 = userRepository.findPage(new Query().addCriteria(BaseCriteria.where("isDelete").is(0).and("type").is(2).and("dutiesCode").is("24")), pof);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (User user : page1.getContent()) {
            UserVo userVo = new UserVo();
            userVo.setUserId(user.getUserId());
            userVo.setDutiyName(user.getDuties());
            userVo.setRealName(user.getRealName());
            userVo.setUrl(user.getPicture());
            userVo.setUserName(user.getUserName());
            userVo.setTime(simpleDateFormat.format(user.getCreateTime()));
            list1.add(userVo);
        }
        for (User user : page2.getContent()) {
            UserVo userVo = new UserVo();
            userVo.setUserId(user.getUserId());
            userVo.setDutiyName(user.getDuties());
            userVo.setRealName(user.getRealName());
            userVo.setUrl(user.getPicture());
            userVo.setUserName(user.getUserName());
            userVo.setTime(simpleDateFormat.format(user.getCreateTime()));
            list2.add(userVo);
        }
        for (User user : page3.getContent()) {
            UserVo userVo = new UserVo();
            userVo.setUserId(user.getUserId());
            userVo.setDutiyName(user.getDuties());
            userVo.setRealName(user.getRealName());
            userVo.setUrl(user.getPicture());
            userVo.setUserName(user.getUserName());
            userVo.setTime(simpleDateFormat.format(user.getCreateTime()));
            list3.add(userVo);
        }
        for (User user : page4.getContent()) {
            UserVo userVo = new UserVo();
            userVo.setUserId(user.getUserId());
            userVo.setDutiyName(user.getDuties());
            userVo.setRealName(user.getRealName());
            userVo.setUrl(user.getPicture());
            userVo.setUserName(user.getUserName());
            userVo.setTime(simpleDateFormat.format(user.getCreateTime()));
            list4.add(userVo);
        }
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        Map<String, Object> map3 = new HashMap<>();
        Map<String, Object> map4 = new HashMap<>();
        map1.put("qiaotaibanList", list1);
        map1.put("total", page1.getTotalElements());
        map2.put("qiaolianList", list2);
        map2.put("total", page2.getTotalElements());
        map3.put("huaqiaoList", list3);
        map3.put("total", page3.getTotalElements());
        map4.put("xzList", list4);
        map4.put("total", page4.getTotalElements());

        list.add(map1);
        list.add(map2);
        list.add(map3);
        list.add(map4);
        return list;
    }

    public long delUser(String userId) {
        User user = findUserById(userId);
        if (user != null) {
            user.setIsDelete(1);
            long l = userRepository.updateByPrimaryKeySelective(user);
            if (l > 0) {
                return 1;
            }
        }
        return 0;
    }

    public long updateUser(String realName, String duties, String userId, String phone) {
        User user = findUserById(userId);
        if (user != null) {
            user.setRealName(realName);
            user.setDuties(duties);
            user.setTelephone(phone);
            long l = userRepository.updateByPrimaryKeySelective(user);
            if (l >= 0) {
                return 1;
            } else {
                return 0;
            }
        }
        return 0;
    }

    public List<Duties> userDutyList(Integer type) {
        List<Duties> list = dutiesRepository.find(new Query().addCriteria(BaseCriteria.where("type").is(type)), null);
        return list;
    }

    public Long findUserByName(String userName, Integer type) {
        long count = userRepository.count(new Query().addCriteria(BaseCriteria.where("userName").is(userName).and("isDelete").is(0).and("type").is(type)));
        return count;
    }

    public Return login(HttpServletResponse response, String username, String password) {
        //查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("UserName").is(username)
                .and("PassWord").is(password)
                .and("IsDelete").is(0));
//        query.addCriteria(Criteria.where("Type").is(2)
//                .and("UserName").is(username)
//                .and("PassWord").is(password)
//                .and("IsDelete").is(0));
        User user = userRepository.findOne(query);
        if (user == null) {
            return new Return(Return.FAIL, "用户名或密码错误");
        }
        Integer type = user.getType();
        if (type != 2) {
            String dutiesCode = user.getDutiesCode();
            if (!dutiesCode.equals("00")
                    && !dutiesCode.equals("01")
                    && !dutiesCode.equals("11")
                    && !dutiesCode.equals("21")
                    && !dutiesCode.equals("31")
                    && !dutiesCode.equals("z1")
                    && !dutiesCode.equals("t1")
                    && !dutiesCode.equals("c1")) {
                return new Return(Return.FAIL, "用户名或密码错误");
            }
        }
        //封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("userInfo", user);
        //基于工具类生成jwt令牌
        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(user), null);
        map.put("token", token);
        //将token放在响应头
        response.setHeader(JwtUtil.AUTH_HEADER_KEY, token);
        return new Return(map);
    }
}

